//
//  BaseViewController.swift
//  Reader
//
//  Created by mn on 2024/9/20.
//

import UIKit
import AVFoundation
enum FileType: String {
    case txt = "txt"
    case mp3 = "mp3"
}

class File {
    let type: FileType
    let name: String
    let path: URL
    var coverImage: UIImage? = nil
    var durtion: Double? = nil
    var durtionString :String? = nil
    init(type: FileType, name: String, path: URL) {
        self.type = type
        self.name = name
        self.path = path
        if type == .mp3{
            let asset = AVURLAsset(url: path)
            let dur = CMTimeGetSeconds(asset.duration)
            self.durtion = dur
            self.durtionString = dur.secondsToHMS()
            for metadataItem in asset.metadata {
                if let commonKey = metadataItem.commonKey,commonKey.rawValue == "artwork" {
                    guard let artworkData = metadataItem.dataValue,
                          let artworkImage = UIImage(data: artworkData) else { continue }
                    self.coverImage = artworkImage
                    break
                }
            }
        }
    }
    
}
extension Double{
    func secondsToHMS() -> String {
        let hour = Int(self / 3600)
        let minute = Int((self.truncatingRemainder(dividingBy: 3600)) / 60)
        let second = Int(self.truncatingRemainder(dividingBy: 60))
        if hour > 0 {
            return String(format: "%02d:%02d:%02d", hour, minute, second)
        } else {
            return String(format: "%02d:%02d", minute, second)
        }
    }
}

class BaseViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    lazy var tableView: UITableView = {
        tableView = UITableView(frame: CGRect(x: 0, y: NavgationBarHeight, width: ScreenWidth, height: ScreenHeight-NavgationBarHeight-TabBarHeight))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.separatorStyle = .none
        view.addSubview(tableView)
        return tableView
    }()
    var files = [File]()
    var currentFile: File?
    
    func setTitle(_ title: String) {
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.title = title
        navigationItem.largeTitleDisplayMode = .automatic
    }
    
    func loadFiles(type:FileType){
        let fileManager = FileManager.default
        files.removeAll()
        if let folderURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
            if let fileURLs = try? fileManager.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil) {
                for fileURL in fileURLs {
                    if fileURL.pathExtension == type.rawValue {
                        files.append(File(type: type, name: fileURL.lastPathComponent, path: fileURL))
                    }
                }
            }
        }
        tableView.reloadData()
    }
    func openFile(url: URL?) {}
    func deleteFile(_ index: Int) {
        
        if let path = (files[index].path as NSURL).path{
            do {
                try FileManager.default.removeItem(atPath: path)
                print("文件删除成功")
            } catch {
                print("文件删除失败，错误信息: \(error)")
            }
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return files.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        cell = cell ?? UITableViewCell(style: .value1, reuseIdentifier: "cell");
        cell?.textLabel?.text = files[indexPath.row].name
        cell?.textLabel?.textColor = UIColor.black
        if let image = files[indexPath.row].coverImage{
            cell?.imageView?.image = image
        }
        if let durtionString = files[indexPath.row].durtionString{
            cell?.detailTextLabel?.text = durtionString
        }
        return cell!
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        currentFile = files[indexPath.row]
        let url = files[indexPath.row].path
        openFile(url: url)
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            deleteFile(indexPath.row)
        }
    }
}
   



